package com.pacy.pacybaseproject.fragments;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.core.widget.NestedScrollView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fondesa.recyclerviewdivider.DividerBuilder;
import com.king.zxing.CameraScan;
import com.king.zxing.CaptureActivity;
import com.lxj.xpopup.XPopup;
import com.pacy.pacybaseproject.BR;
import com.pacy.pacybaseproject.R;
import com.pacy.pacybaseproject.activitys.AcDetailActivity;
import com.pacy.pacybaseproject.base.BaseXFragment;
import com.pacy.pacybaseproject.databinding.FragmentHomeBinding;
import com.pacy.pacybaseproject.popups.CheckInPopup;
import com.pacy.pacybaseproject.popups.ClockSuccessPopup;
import com.pacy.pacybaseproject.utils.LocationService;
import com.pacy.pacybaseproject.viewmodels.HomeViewModel;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.xuexiang.xui.utils.SnackbarUtils;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.utils.ViewUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ScreenUtil;
import me.goldze.mvvmhabit.utils.StringUtils;

/**
 * @author PACY
 * @date 2023/12/20
 * description: 首页
 */
public class HomeFragment extends BaseXFragment<FragmentHomeBinding, HomeViewModel> {
    /**
     * 定位权限
     */
    private String[] locationPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };
    private RxPermissions rxPermissions;
    private LocationClient mLocationClient;
    private LocationClientOption option = new LocationClientOption();
    private BDLocation bdLocation;
    public static HomeFragment newInstance(String title) {

        Bundle args = new Bundle();
        args.putString("title", title);
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int initContentView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        return R.layout.fragment_home;
    }
 
    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        ViewUtils.setPaddingTop( binding.homeTopView, StatusBarUtils.getStatusBarHeight(getContext())+ScreenUtil.dp2px(8));
        if (binding.homeMenuRv.getItemDecorationCount() == 0) {
            new DividerBuilder(getContext())
                    .size(12, TypedValue.COMPLEX_UNIT_DIP)
                    .color(Color.TRANSPARENT)
                    .showFirstDivider()
                    .showLastDivider()
                    .build().addTo(binding.homeMenuRv);
        }
        if (binding.homeMsgRv.getItemDecorationCount() == 0) {
            new DividerBuilder(getContext())
                    .size(10, TypedValue.COMPLEX_UNIT_DIP)
                    .color(Color.TRANSPARENT)
//                    .showFirstDivider()
//                    .showLastDivider()
                    .build().addTo(binding.homeMsgRv);
        }

        if (binding.homeActivityRv.getItemDecorationCount() == 0) {
            new DividerBuilder(getContext())
                    .size(12, TypedValue.COMPLEX_UNIT_DIP)
                    .color(Color.TRANSPARENT)
//                    .showFirstDivider()
//                    .showLastDivider()
                    .build().addTo(binding.homeActivityRv);
        }
        binding.scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//                KLog.i("scrollX="+scrollX+"  oldScrollX="+oldScrollX+"  scrollY="+scrollY+"  oldScrollY="+oldScrollY);
                if(scrollY>oldScrollY){//向下滑动

                }
                if(scrollY==0){
                    KLog.i("到顶部");
                }

                if(scrollY==(v.getChildAt(0).getMeasuredHeight()-v.getMeasuredHeight())){
                    KLog.i("到底部");
                }
            }
        });

        binding.qrCodeHiv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getContext(), CaptureActivity.class), 999);
            }
        });

        initPermissions();

        binding.selectCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickCity();
            }
        });
    }

    /**
     * 选择城市
     */
    private void pickCity() {
        LocatedCity myLocate=null;
        if(bdLocation!=null){
            myLocate=new LocatedCity(bdLocation.getCity(), bdLocation.getProvince(), bdLocation.getAdCode());
        }
        CityPicker.from(this)
                .enableAnimation(true)
                .setLocatedCity(myLocate)
                .setHotCities(null)
                .setOnPickListener(new OnPickListener() {
                    @Override
                    public void onPick(int position, City data) {
                        viewModel.cityName.setValue(data.getName());
//                        XToastUtils.toast(String.format("点击的数据：%s，%s", data.getName(), data.getCode()));
                    }

                    @Override
                    public void onCancel() {
                        XToastUtils.toast("取消选择");
                    }

                    @Override
                    public void onLocate() {
                        //开始定位
//                        mListener.setOnLocationListener(locationListener);
//                        LocationService.start(mListener);
//                                new Handler().postDelayed(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        //模拟定位成功
//                                        if(bdLocation!=null){
//                                            CityPicker.from(HomeFragment.this)
//                                                    .locateComplete(new LocatedCity(bdLocation.getCity(), bdLocation.getProvince(), bdLocation.getAdCode()), LocateState.SUCCESS);
//                                        }
//                                    }
//                                }, 2000);
                    }
                })
                .show();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999) {
            String result = CameraScan.parseScanResult(data);
            KLog.i(result);
            new XPopup.Builder(getContext()).asCustom(new CheckInPopup(getContext())).show();
        }
    }

    private void initPermissions(){
        rxPermissions = new RxPermissions(this);
        rxPermissions.request(locationPermissions).subscribe(aBoolean -> {
            if(aBoolean){
                initLocation();
            }else{
                ToastUtils.showShort("未授予权限，部分功能可能出现异常");
            }
        });
    }

    private void initLocation(){
        try {
            mLocationClient.setAgreePrivacy(true);
            mLocationClient=new LocationClient(getContext().getApplicationContext());
            option.setCoorType("bd09ll"); // 设置坐标类型
            //可选，是否需要位置描述信息，默认为不需要，即参数为false
            option.setIsNeedLocationDescribe(true);
            //是否需要地址信息
            option.setIsNeedAddress(true);
            //设置locationClientOption
            mLocationClient.setLocOption(option);
            //注册LocationListener监听器
            mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
                @Override
                public void onReceiveLocation(BDLocation location) {
                    if (location == null){
                        KLog.i("location为空");
                        return;
                    }
                    bdLocation=location;
                    String addr = location.getAddrStr();    //获取详细地址信息
                    String country = location.getCountry();    //获取国家
                    String province = location.getProvince();    //获取省份
                    String city = location.getCity();    //获取城市
                    String district = location.getDistrict();    //获取区县
                    String street = location.getStreet();    //获取街道信息
                    String adcode = location.getAdCode();    //获取adcode
                    String town = location.getTown();    //获取乡镇信息

                    KLog.i(country+"-"+province+"-"+city+"-"+district+"-"+town+"-"+street+"-"+adcode+"-"+addr);
                    viewModel.cityName.setValue(StringUtils.isEmpty(city)?"未知":city);
                    viewModel.showCity.setValue(true);

                    mLocationClient.stop();


                }
            });
            //开启定位
            mLocationClient.start();
        } catch (Exception e) {
            e.printStackTrace();
            KLog.i(e.toString());
            ToastUtils.showShort("定位失败");
        }
    }


}
